package com.xjoyt.pay.master.core.order.handle.callback;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.CallbackParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCallbackHandle;
import com.xjoyt.pay.master.dto.CallbackResult;
import com.xjoyt.pay.master.po.MerchantMoney;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.repository.MerchantMoneyRepository;
import com.xjoyt.pay.vo.MoneyType;

/**
 * 处理流水
 * 
 * @author Administrator
 *
 */
@Component
public class MoneyHandle extends AbstractOrderCallbackHandle {

	@Autowired
	private MerchantMoneyRepository merchantMoneyRepository;

	@Override
	public ExecuteResult<CallbackResult> handle(CallbackParam param, Order order) throws Exception {
		// // 付款
		// List<MerchantMoney> list = new ArrayList<>();
		// list = merchantMoneyRepository.findAllByNoAndType(order.no,
		// MoneyType.TRADE.toString());
		// list.addAll(merchantMoneyRepository.findAllByNoAndType(order.no,
		// MoneyType.PAY_POUNDAGE_ADD.toString()));
		//
		// if (CollectionUtils.isNotEmpty(list)) {
		// return ExecuteResult.fail("数据已存在");
		// }

		if (merchantMoneyRepository.findOneByNoAndType(order.no, MoneyType.TRADE) == null) {
			MerchantMoney po = new MerchantMoney();
			po.merchant = order.merchant;
			po.no = order.no;
			po.channel = order.orderConfig.channel;
			po.type = MoneyType.TRADE;
			po.money = order.money;
			po.addedDate = new Date();
			merchantMoneyRepository.save(po);
		}

		// 扣除手续费
		if (merchantMoneyRepository.findOneByNoAndType(order.no, MoneyType.TRADE_POUNDAGE_ADD) == null) {
			MerchantMoney po = new MerchantMoney();
			po.merchant = order.merchant;
			po.no = order.no;
			po.channel = order.orderConfig.channel;
			po.type = MoneyType.TRADE_POUNDAGE_ADD;
			double rate = order.rate == null ? 0D : order.rate;
			// po.money = -(long) (rate * (double) order.money / 1000D);
			po.money = -(long) (rate * (double) order.money / 100D);

			po.addedDate = new Date();
			merchantMoneyRepository.save(po);
		}

		// order.poundage = po.money;
		// order = repository.save(order);

		return getNext().handle(param, order);
	}

}
